<?php
/**
 * Created by PhpStorm.
 * User: long
 * Date: 2016/9/25
 * Time: 14:05
 */

namespace Notify\Controller;


use Common\Model\CardModel;
use Common\Model\MemberModel;
use Common\Model\MemCardModel;
use Common\Model\OrderModel;
use Think\Log;


/**
 * 微信支付
 * Class WxpayController
 * @package Notify\Controller
 */
class WxpayController extends NotifybaseController
{

    public $order_model;

    public $member_model;
    public $card_model;
    public $mem_card_model;


    public function __construct()
    {
        parent::__construct();
        $this->order_model          = new OrderModel();

        $this->member_model         = new MemberModel();
        $this->card_model           = new CardModel();
        $this->mem_card_model       = new MemCardModel();


        header("Content-type:text/html;charset=utf-8");
        ini_set('date.timezone', 'Asia/Shanghai');
        vendor('WxPayPubHelper.WxPayPubHelper');
    }

    public function index()
    {
        Log::record(json_encode(I(''), Log::WARN));
        //使用通用通知接口
        $notify = new \Notify_pub();
        //存储微信的回调
//        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        $xml = file_get_contents('php://input');
        //回调错误
        if (!$xml) {
//            Log::record('global参数:' . json_encode($GLOBALS), Log::WARN);
            Log::record('微信支付回调校验失败1:' . json_encode(I('')), Log::WARN);
            return false;
        }

        $notify->saveData($xml);
        //签名状态
        $checkSign = true;
        //验证签名，并回应微信。
        //对后台通知交互时，如果微信收到商户的应答不是成功或超时，微信认为通知失败，
        //微信会通过一定的策略（如30分钟共8次）定期重新发起通知，
        //尽可能提高通知的成功率，但微信不保证通知最终能成功。
        if ($notify->checkSign() == FALSE) {
            $notify->setReturnParameter("return_code", "FAIL");//返回状态码
            $notify->setReturnParameter("return_msg", "签名失败");//返回信息
            $checkSign = false;
        } else {
            $notify->setReturnParameter("return_code", "SUCCESS");//设置返回码
        }
        $returnXml = $notify->returnXml();



        if (!$checkSign) {
            Log::record('微信支付回调校验失败2:' . json_encode(I('')), Log::WARN);
            exit;
        }

        //通知微信，成功获取到相应的异步通知
        echo $returnXml;

        //微信返回参数
        $back_data = $notify->getData();

        $order_sn = $back_data['out_trade_no']; //订单号


        $order = $this->order_model->where(['order_sn' => $order_sn])->find();
        //dump($order);die;
        if (!$order) {
            Log::record($order_sn . '订单编号不存在', Log::WARN);
            exit('fail');
        }

        $time = date('Y-m-d H:i:s');
        $data = [
            'status'        => 'payed',
            'pay_time'      => $time,
            'back_data'     => json_encode($back_data),
            'update_time'   => $time,
            'card_info'     => json_encode($this->card_model->find($order['card_id'])),
        ];

        $result = $this->order_model->where(['order_sn' => $order_sn])->save($data);
        $card_info = $this->card_model->find($order['card_id']);
        $member_info = $this->member_model->find($order['mid']);
        $mem_card = $this->mem_card_model->where(['phone' => $member_info['phone']])->find();
        if($mem_card) {//非首次购买卡，删除原来的
            $this->mem_card_model->where(['phone' => $member_info['phone']])->delete();
        }
        if($card_info['type'] == 'times') {//次数卡
            $card_data = [
                'phone' => $member_info['phone'],
                'type'  => $card_info['type'],
                'times' => $card_info['number'],
                'end_time'  => date('Y-m-d H:i:s', time()+$card_info['enable_day']*3600*24),
                'number'    => $card_info['number'],
                'parent'    => $order['name'],
                'create_time'   => $time,
            ];

        } else {
            $card_data = [
                'phone' => $member_info['phone'],
                'type'  => $card_info['type'],
                'times' => 0,
                'end_time'  => date('Y-m-d H:i:s', time()+$card_info['number']*3600*24),
                'number'    => $card_info['number'],
                'parent'    => $order['name'],
                'create_time'   => $time,
            ];
        }

//        dump($card_data);die;
        $this->mem_card_model->add($card_data);
    }


}